package com.example.mqttclient;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.mqttclient.mqtt.MqttService;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textview.MaterialTextView;

import org.eclipse.paho.client.mqttv3.MqttException;

public class MainActivity extends AppCompatActivity implements MqttService.MqttEventCallBack {
    private MaterialTextView connectState;
    private ProgressBar connectionProgress;
    private MaterialCardView connectionCard;
    private MqttService.MqttBinder mqttBinder;
    private final String TAG = "MainActivity";

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mqttBinder = (MqttService.MqttBinder)iBinder;
            mqttBinder.setMqttEventCallBack(MainActivity.this);
            updateConnectionUI(mqttBinder.isConnected());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mqttBinder = null;
        }
    };

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        connectState = findViewById(R.id.connect_state);
        connectionProgress = findViewById(R.id.connection_progress);
        connectionCard = findViewById(R.id.connection_card);

        // 绑定MQTT服务
        Intent mqttServiceIntent = new Intent(this, MqttService.class);
        startService(mqttServiceIntent);
        bindService(mqttServiceIntent, connection, Context.BIND_AUTO_CREATE);

        // 设置按钮点击事件
        findViewById(R.id.settings_btn).setOnClickListener(view ->
                startActivity(new Intent(this, SettingsActivity.class)));

        findViewById(R.id.pubsub_test_btn).setOnClickListener(view ->
                startActivity(new Intent(this, PubSubTestActivity.class)));

        findViewById(R.id.dev_demo_btn).setOnClickListener(view ->
                startActivity(new Intent(this, DevicesDemoActivity.class)));
    }

    private void updateConnectionUI(boolean isConnected) {
        runOnUiThread(() -> {
            if (isConnected) {
                connectState.setText("已连接");
                connectState.setTextColor(ContextCompat.getColor(this, R.color.connected));
                connectionCard.setStrokeColor(ContextCompat.getColor(this, R.color.connected));
                connectionProgress.setVisibility(View.GONE);
            } else {
                connectState.setText("未连接");
                connectState.setTextColor(ContextCompat.getColor(this, R.color.disconnected));
                connectionCard.setStrokeColor(ContextCompat.getColor(this, R.color.disconnected));
                connectionProgress.setVisibility(View.VISIBLE);
            }
        });
    }

    void subscribeTopics() {
        try {
            if (mqttBinder != null) {
                mqttBinder.subscribe("/test");
            }
        } catch (MqttException e) {
            Log.e(TAG, "订阅主题失败", e);
        }
    }

    void unSubscribeTopics() {
        try {
            if (mqttBinder != null) {
                mqttBinder.unSubscribe("/test");
            }
        } catch (MqttException e) {
            Log.e(TAG, "取消订阅失败", e);
        }
    }

    @Override
    public void onConnectSuccess() {
        updateConnectionUI(true);
        subscribeTopics();
    }

    @Override
    public void onConnectError(String error) {
        Log.e(TAG, "连接错误: " + error);
        updateConnectionUI(false);
    }

    @Override
    public void onDeliveryComplete() {
        Log.d(TAG, "消息发布成功");
    }

    @Override
    public void onMqttMessage(String topic, String message) {
        Log.d(TAG, "收到消息 - 主题: " + topic + ", 内容: " + message);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mqttBinder != null) {
            updateConnectionUI(mqttBinder.isConnected());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unSubscribeTopics();
    }

    @Override
    protected void onDestroy() {
        if (mqttBinder != null) {
            unbindService(connection);
        }
        super.onDestroy();
    }
}